/**
 * 目前仅添加了位置、摄像头、存储、拨打电话权限，其他权限可根据需求自行添加
 */

var isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif



export const LOCATION = "ACCESS_FINE_LOCATION" //位置权限
export const CAMERA = "CAMERA" //摄像头权限
export const READ_STORAGE = "READ_EXTERNAL_STORAGE" //外部存储(含相册)读取权限
export const WRITE_STORAGE = "WRITE_EXTERNAL_STORAGE" //外部存储(含相册)写入权限
export const CALL_PHONE = "CALL_PHONE" //拨打电话权限

/* const contentMap = {
	[READ_STORAGE]: {
		title: "存储空间/照片权限申请说明",
		content: "我们访问您的相册权限以访问您相册中的图片及视频,以为您提供修改头像，上传图片等服务;您可以保存图片、发送图片消息。",
		permissionId :""
	},
	[LOCATION]: {
		title: "地理位置权限申请说明",
		content: "我们需要获取当前位置，以便进行骑手定位或查看客户地址。",
		permissionId :""
	},
	[CALL_PHONE]: {
		title: "拨打/管理电话权限申请说明",
		content: "我们需要获取电话权限，以便拨打电话。",
		permissionId :""
	},
	[CAMERA]: {
		title: '相机权限使用说明',
		content: '我们访问您的相机权限是为了获取您所拍摄的照片及视频,以为您提供修改头像，上传图片等服务;您可以发送图片消息,上传所需图片,设置头像。',
		permissionId :""
	},
} */

// 判断推送权限是否开启
function judgeIosPermissionPush() {
	var result = false;
	var UIApplication = plus.ios.import("UIApplication");
	var app = UIApplication.sharedApplication();
	var enabledTypes = 0;
	if (app.currentUserNotificationSettings) {
		var settings = app.currentUserNotificationSettings();
		enabledTypes = settings.plusGetAttribute("types");
		console.log("enabledTypes1:" + enabledTypes);
		if (enabledTypes == 0) {
			console.log("推送权限没有开启");
		} else {
			result = true;
			console.log("已经开启推送功能!")
		}
		plus.ios.deleteObject(settings);
	} else {
		enabledTypes = app.enabledRemoteNotificationTypes();
		if (enabledTypes == 0) {
			console.log("推送权限没有开启!");
		} else {
			result = true;
			console.log("已经开启推送功能!")
		}
		console.log("enabledTypes2:" + enabledTypes);
	}
	plus.ios.deleteObject(app);
	plus.ios.deleteObject(UIApplication);
	return result;
}

// 判断定位权限是否开启
function judgeIosPermissionLocation() {
	var result = false;
	var cllocationManger = plus.ios.import("CLLocationManager");
	var status = cllocationManger.authorizationStatus();
	result = (status != 2)
	console.log("定位权限开启：" + result);
	// 以下代码判断了手机设备的定位是否关闭，推荐另行使用方法 checkSystemEnableLocation
	/* var enable = cllocationManger.locationServicesEnabled();
	var status = cllocationManger.authorizationStatus();
	console.log("enable:" + enable);
	console.log("status:" + status);
	if (enable && status != 2) {
		result = true;
		console.log("手机定位服务已开启且已授予定位权限");
	} else {
		console.log("手机系统的定位没有打开或未给予定位权限");
	} */
	plus.ios.deleteObject(cllocationManger);
	return result;
}

// 判断麦克风权限是否开启
function judgeIosPermissionRecord() {
	var result = false;
	var avaudiosession = plus.ios.import("AVAudioSession");
	var avaudio = avaudiosession.sharedInstance();
	var permissionStatus = avaudio.recordPermission();
	console.log("permissionStatus:" + permissionStatus);
	if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
		console.log("麦克风权限没有开启");
	} else {
		result = true;
		console.log("麦克风权限已经开启");
	}
	plus.ios.deleteObject(avaudiosession);
	return result;
}

// 判断相机权限是否开启
function judgeIosPermissionCamera() {
	var result = false;
	var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
	var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
	console.log("authStatus:" + authStatus);
	if (authStatus == 3) {
		result = true;
		console.log("相机权限已经开启");
	} else {
		console.log("相机权限没有开启");
	}
	plus.ios.deleteObject(AVCaptureDevice);
	return result;
}

// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary() {
	var result = false;
	var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
	var authStatus = PHPhotoLibrary.authorizationStatus();
	console.log("authStatus:" + authStatus);
	if (authStatus == 3) {
		result = true;
		console.log("相册权限已经开启");
	} else {
		console.log("相册权限没有开启");
	}
	plus.ios.deleteObject(PHPhotoLibrary);
	return result;
}

// 判断通讯录权限是否开启
function judgeIosPermissionContact() {
	var result = false;
	var CNContactStore = plus.ios.import("CNContactStore");
	var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
	if (cnAuthStatus == 3) {
		result = true;
		console.log("通讯录权限已经开启");
	} else {
		console.log("通讯录权限没有开启");
	}
	plus.ios.deleteObject(CNContactStore);
	return result;
}

// 判断日历权限是否开启
function judgeIosPermissionCalendar() {
	var result = false;
	var EKEventStore = plus.ios.import("EKEventStore");
	var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
	if (ekAuthStatus == 3) {
		result = true;
		console.log("日历权限已经开启");
	} else {
		console.log("日历权限没有开启");
	}
	plus.ios.deleteObject(EKEventStore);
	return result;
}

// 判断备忘录权限是否开启
function judgeIosPermissionMemo() {
	var result = false;
	var EKEventStore = plus.ios.import("EKEventStore");
	var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
	if (ekAuthStatus == 3) {
		result = true;
		console.log("备忘录权限已经开启");
	} else {
		console.log("备忘录权限没有开启");
	}
	plus.ios.deleteObject(EKEventStore);
	return result;
}

// Android权限查询
function requestAndroidPermission(permissionID) {
	console.log('permissionID: ',permissionID);
	return new Promise((resolve, reject) => {
		plus.android.requestPermissions(
			[permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
			function(e) {
				console.log('e: ',e);
				let result = 0;
				if (e.granted.length > 0) {
					//用户同意
					result = 1
				}
				if (e.deniedPresent.length > 0) {
					//用户拒绝
					result = 0
				}
				if (e.deniedAlways.length > 0) {
					//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
					result = -1
				}
				resolve(result);
			},
			function(error) {
				resolve({
					code: error.code,
					message: error.message
				});
			}
		);
	});
}

// 使用一个方法，根据参数判断权限
function judgeIosPermission(permissionID) {
	if (permissionID == "location") {
		return judgeIosPermissionLocation()
	} else if (permissionID == "camera") {
		return judgeIosPermissionCamera()
	} else if (permissionID == "photoLibrary") {
		return judgeIosPermissionPhotoLibrary()
	} else if (permissionID == "record") {
		return judgeIosPermissionRecord()
	} else if (permissionID == "push") {
		return judgeIosPermissionPush()
	} else if (permissionID == "contact") {
		return judgeIosPermissionContact()
	} else if (permissionID == "calendar") {
		return judgeIosPermissionCalendar()
	} else if (permissionID == "memo") {
		return judgeIosPermissionMemo()
	}
	return false;
}

// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {
	if (isIos) {
		var UIApplication = plus.ios.import("UIApplication");
		var application2 = UIApplication.sharedApplication();
		var NSURL2 = plus.ios.import("NSURL");
		// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");		
		var setting2 = NSURL2.URLWithString("app-settings:");
		application2.openURL(setting2);

		plus.ios.deleteObject(setting2);
		plus.ios.deleteObject(NSURL2);
		plus.ios.deleteObject(application2);
	} else {
		// console.log(plus.device.vendor);
		var Intent = plus.android.importClass("android.content.Intent");
		var Settings = plus.android.importClass("android.provider.Settings");
		var Uri = plus.android.importClass("android.net.Uri");
		var mainActivity = plus.android.runtimeMainActivity();
		var intent = new Intent();
		intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
		intent.setData(uri);
		mainActivity.startActivity(intent);
	}
}

// 检查系统的设备服务是否开启
// var checkSystemEnableLocation = async function () {
function checkSystemEnableLocation() {
	if (isIos) {
		var result = false;
		var cllocationManger = plus.ios.import("CLLocationManager");
		var result = cllocationManger.locationServicesEnabled();
		console.log("系统定位开启:" + result);
		plus.ios.deleteObject(cllocationManger);
		return result;
	} else {
		var context = plus.android.importClass("android.content.Context");
		var locationManager = plus.android.importClass("android.location.LocationManager");
		var main = plus.android.runtimeMainActivity();
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		var result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
		console.log("系统定位开启:" + result);
		return result
	}
}

//提示框
function nativeObjView(options) {
	const systemInfo = uni.getSystemInfoSync();
	const statusBarHeight = systemInfo.statusBarHeight;
	const navigationBarHeight = systemInfo.platform === 'android' ? 48 :
		44; // Set the navigation bar height based on the platform
	const totalHeight = statusBarHeight + navigationBarHeight;
	
	let view = new plus.nativeObj.View(options.permissionID, {
		top: '0px',left: '0px',width: '100%',
		//backgroundColor: '#444',
		//opacity: .5;
	})
	
	view.drawRect(
	{color: '#fff',radius: '6px', borderWidth: "1px",borderColor: "#ddd"}, 
	{top: totalHeight + 'px',left: '5%',width: '90%',height: "100px",}
	)
	
	//提示标题
	view.drawText(options.title??'权限使用说明', 
	{top: totalHeight + 5 + 'px',left: "8%",height: "30px"}, 
	{align: "left",color: "#000",})
	
	//提示内容
	view.drawText(options.content, 
	{top: totalHeight + 35 + 'px',height: "60px",left: "8%",width: "84%"}, 
	{whiteSpace: 'normal',size: "14px",align: "left",color: "#656563"})

	function show() {
		setTimeout(() =>{
			view = plus.nativeObj.View.getViewById(options.permissionID);
			view.show()
			view = null //展示的时候也得清空，不然影响下次的关闭，不知道为啥
		}, 500)
	}

	function close() {
		view = plus.nativeObj.View.getViewById(options.permissionID);
		view.close();
		view = null
	}
	return {
		show,
		close
	}
}

// 检查授权
const requestAppPermission = async (options) => {
	
	const pid = 'android.permission.' + options.permissionID;
	return new Promise((resolve, reject) => {
		plus.android.checkPermission(pid, 
			granted => {
				console.log('granted: ',granted);
				if (granted.checkResult !== -1) {
					resolve(1)
					return
				}
				const viewObj = nativeObjView(options);
				viewObj.show();
				
				requestAndroidPermission(pid).then(res => {
					if(res === 1 || res === 0) {
						if (viewObj) viewObj.close()
					}
					
					//首次拒绝
					if (res === 0) {
						resolve(-1)
						return
					}
					
					if (res === 1) {
						resolve(1)
						return
					}
					if (res === -1) {
						// 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
						uni.showModal({
							title: '温馨提示',
							content: '还没有该权限，立即去设置开启？',
							cancelText: "取消",
							confirmText: "去设置",
							showCancel: true,
							confirmColor: '#000',
							cancelColor: '#666',
							success: res => {
								if (res.confirm) {
									gotoAppPermissionSetting()
								}
								if (res.cancel) {
									resolve(-1)
								}
							},
							complete: () => {
								if (viewObj) viewObj.close()
							}
						});
					}
				})
			})
	})

}

export const usePermissions = () => {
	return {
		requestAppPermission,
		judgeIosPermission
	}
}